using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class OptionUI : MonoBehaviour
{
    public Text optionText;

    private Button optionBtn;

    private DialoguePiece currentPiece;

    private string nextPieceID;
    private bool takeQuest;
    private bool openShop;
    private InventoryData_SO shopData;


    private void Awake()
    {
        optionBtn = GetComponent<Button>();
        optionBtn.onClick.AddListener(OnOptionClicked);
    }

    public void updateOption(DialoguePiece piece, DialogueOption option)
    {
        currentPiece = piece;
        optionText.text = option.text;
        nextPieceID = option.targetId;
        takeQuest = option.takeQuest;
        openShop = option.openShop;
        shopData = option.shopData;
    }

    public void OnOptionClicked()
    {
        if (openShop)
        {
            DialogueManager.Instance.dialoguePanel.SetActive(false);
            InventoryManager.Instance.shopData = Instantiate(shopData);
            InventoryManager.Instance.shop.SetActive(true);
            InventoryManager.Instance.bag.SetActive(true);
        }
        if (currentPiece.Quest != null)
        {
            //创造一个临时变量，克隆原本的任务，可以修改任务进度
            var newTask = new QuestManager.QuestTask {QuestData = Instantiate(currentPiece.Quest)};
            if (takeQuest)
            {
                if (QuestManager.Instance.HaveQuest(currentPiece.Quest))
                {
                    if (QuestManager.Instance.GetTask(currentPiece.Quest).IsComplete)
                    {
                        currentPiece.Quest.GiveRewards();
                        QuestManager.Instance.GetTask(currentPiece.Quest).IsFinished = true;
                    }
                }
                else
                {
                    QuestManager.Instance.QuestTasks.Add(newTask);
                    QuestManager.Instance.GetTask(currentPiece.Quest).IsStarted = true;

                    foreach (var requireName in newTask.QuestData.RequireTargetName())
                    {
                        InventoryManager.Instance.CheckQuestItemInBag(requireName);
                    }
                }
            }
        }
        if (nextPieceID == "")
        {
            DialogueManager.Instance.dialoguePanel.SetActive(false);
            return;
        }
        else
        {
            DialogueManager.Instance.updateDialougueUI(DialogueManager.Instance.currentData.DialogueDictionary[nextPieceID]);
        } 
    }
}
